package com.store.framework.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.store.framework.context.SystemServletKey;
import com.store.framework.entry.AppAdmin;

/**
 * @author 'Yao Jian'
 * 
 */
public class SessionListener implements HttpSessionListener {

	private static Log LOG = LogFactory.getLog(SessionListener.class);

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());

		String mess = String.format("session created: time[%s],sessionid[%s]",
				now, se.getSession().getId());

		LOG.info(mess);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		AppAdmin adminPojo = (AppAdmin) session
				.getAttribute(SystemServletKey.LOGIN_ADMINUSER_INFO);
		String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		String mess = String.format(
				"session destroyed: time[%s],sessionid[%s]", now,
				session.getId());
		System.out.println(mess);
		if (adminPojo != null) {
			mess = String.format(
					"session destroyed: time[],sessionid[%s],username:[%s]",
					now, session.getId(),
					(adminPojo != null ? adminPojo.getAdName() : ""));

			session.removeAttribute(SystemServletKey.LOGIN_ADMINUSER_INFO);
		}
		LOG.info(mess);
	}

}
